#include "IpDealer.h"
#ifdef Q_OS_Windows
#include <iostream>
#include <iphlpapi.h>
#endif
using namespace std;

IpDealer::IpDealer() {
#ifdef Q_OS_Windows
  WSAData data;
  WSAStartup(MAKEWORD(1, 1), &data);
#endif
}

IpDealer::~IpDealer() {
#ifdef Q_OS_Windows
  WSACleanup();
#endif
}

std::string IpDealer::getTip() const { return m_strTips__; }

std::vector<std::string> IpDealer::getIpList() {
  std::vector<std::string> result;
#ifdef Q_OS_Windows
  char name[256];
  char tips[256];

  int getNameRet = gethostname(name, sizeof(name));
  snprintf(tips, sizeof(tips), "gethostname,ret:%d,errCode:%d,name:%s.\n",
           getNameRet, WSAGetLastError(), name);
  m_strTips__ += tips;

  hostent *host = gethostbyname(name);
  snprintf(tips, sizeof(tips), "gethostbyname,errCode:%d.\n",
           WSAGetLastError());
  m_strTips__ += tips;

  cout << "host len," << strlen((char *)host) << endl;
  cout << (char *)host << endl;

  if (NULL == host) {
    return result;
  }

  in_addr *pAddr = (in_addr *)*host->h_addr_list;

  cout << strlen((char *)pAddr) << endl;
  cout << (char *)pAddr << endl;

  for (int i = 0; i < 4; i++) {
    string addr = inet_ntoa(pAddr[i]);
    cout << addr.c_str() << endl;
    result.push_back(addr);
  }

#endif
  return result;
}

std::vector<string> IpDealer::getAdptInfo() {
  vector<string> result;
#ifdef Q_OS_Windows
  IP_ADAPTER_INFO *pAdpFree = NULL;
  IP_ADAPTER_INFO *pIpAdpInfo =
      (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO));
  unsigned long ulBufLen = sizeof(IP_ADAPTER_INFO);
  int ret;
  if ((ret = GetAdaptersInfo(pIpAdpInfo, &ulBufLen)) == ERROR_BUFFER_OVERFLOW) {
    free(pIpAdpInfo);
    pIpAdpInfo = (IP_ADAPTER_INFO *)malloc(ulBufLen);
    if (NULL == pIpAdpInfo) {
      return result;
    }
  }

  char ip[256];
  if ((ret = GetAdaptersInfo(pIpAdpInfo, &ulBufLen)) == NO_ERROR) {
    pAdpFree = pIpAdpInfo;

    for (int i = 0; pIpAdpInfo; i++) {
      string addr;
      snprintf(ip, sizeof(ip), "netcard%d ip addr:", i);
      addr += ip;
      IP_ADDR_STRING *pIps = &pIpAdpInfo->IpAddressList;
      while (pIps) {
        snprintf(ip, sizeof(ip), "ip:%s,mask:%s,gate:%s.",
                 pIps->IpAddress.String, pIps->IpMask.String,
                 pIpAdpInfo->GatewayList.IpAddress.String);
        addr += ip;
        cout << pIps->IpAddress.String << endl;
        cout << pIps->IpMask.String << endl;
        cout << pIpAdpInfo->GatewayList.IpAddress.String << endl;
        pIps = pIps->Next;
      }
      result.push_back(addr);
      pIpAdpInfo = pIpAdpInfo->Next;
    }
  }
  if (pAdpFree) {
    free(pAdpFree);
  }
#endif
  return result;
}
